from apps.pojo.Entity import User, db


class UserDao:
    @staticmethod
    def list(username, offset, limit):
        return User.query.filter(User.username.like("%"+username+"%")).offset(offset).limit(limit).all()

    @staticmethod
    def count():
        return User.query.count()

    @staticmethod
    def getUserById(id):
        return User.query.filter_by(id=id).first()

    @staticmethod
    def add(user):
        try:
            db.session.add(user)
            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            print(e)
            return False
    @staticmethod
    def update(id, username, password):
        user = User.query.filter_by(id=id).first()
        user.username = username
        user.password = password
        try:
            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            print(e)
            return False

    @staticmethod
    def delete(id):
        try:
            User.query.filter_by(id=id).delete()
            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            print(e)
            return False
